#include "core.h"
#include "log.h"
#include "render_dx9.h"
#include "render_ogl.h"

core::core()
{
	m_game = 0;
	m_window = 0;
	m_render = 0;
}

core::~core()
{

}

render* core::get_render()
{
	return m_render;
}

window* core::get_window()
{
	return m_window;
}

game* core::get_game()
{
	return m_game;
}

void core::exit_game()
{
	m_exitflag = true;
}

void core::run(const char* _fname,game* _game)
{
	if(m_window!=0 || m_render!=0)
	{
		LOG_FATAL("Core already initiated.");
	}

	xml_document doc;
	doc.parse_file(_fname);

	m_window = new window(doc["window"]);
	m_render = new render_ogl();

	m_render->init(doc["render"]);

	m_input = input::get_ptr();

	m_update_delay = doc["game"].attr_int("update_delay",16);
	m_render_delay = doc["game"].attr_int("render_delay",0);

	m_pathmngr = pathmngr::get_ptr();

	if(doc.check_child("pathmngr"))
		m_pathmngr->init(doc["pathmngr"]);

	if(!_game)
		LOG_FATAL("Game class instance error.");

	m_game = _game;

	MSG msg;

	if(m_game)
		m_game->create(doc["game"]);

	m_render_timer = 0;
	m_update_timer = 0;
	u32 dt = 0;
	u32 time = 0;

	m_exitflag = false;

	while(!m_exitflag)
	{
		time = GetTickCount();

		if(m_game)
		{
			dt = time-m_update_timer;
			input::get_inst().update();
			if(dt>m_update_delay)
			{
				m_game->update(dt);
				m_update_timer = time;
			}
			dt = time-m_render_timer;
			if(dt>m_render_delay)
			{
				m_game->draw();
				m_render_timer = time;
			}
		}

		if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			if(msg.message==WM_QUIT)
				break;
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	if(m_game)
		m_game->destroy();

	delete m_input;
	delete m_game;
	delete m_render;
	delete m_window;
	delete m_pathmngr;
}